'use strict';

const MarkdownIt = require('markdown-it');
const validator = require('validator');
const jsxss = require('xss');
const moment = require('moment');
const bcrypt = require('bcryptjs');
const axios = require('axios');
const {chromium, devices} = require('playwright');
const _ = require('lodash');
const got = require('../utils/got');

moment.locale('zh-cn'); // 使用中文

// Set default options
const md = new MarkdownIt();
md.use(require('markdown-it-checkbox'), {
  idPrefix: 'task_list_item'
});


md.set({
  html: false, // Enable HTML tags in source
  xhtmlOut: false, // Use '/' to close single tags (<br />)
  breaks: true, // Convert '\n' in paragraphs into <br>
  linkify: true, // Autoconvert URL-like text to links
  typographer: true, // Enable smartypants and other sweet transforms
});

md.renderer.rules.fence = (tokens, idx) => {
  const token = tokens[idx];
  let language = (token.info && 'language-' + token.info) || '';
  language = validator.escape(language);

  return (
    '<pre class="prettyprint ' +
    language +
    '">' +
    '<code>' +
    validator.escape(token.content) +
    '</code>' +
    '</pre>'
  );
};

md.renderer.rules.code_block = (tokens, idx /* , options */) => {
  const token = tokens[idx];

  return (
    '<pre class="prettyprint">' +
    '<code>' +
    validator.escape(token.content) +
    '</code>' +
    '</pre>'
  );
};

const myxss = new jsxss.FilterXSS({
  onIgnoreTag(tag, html, options) {
    if (tag == 'input') {
      return html;
    }
    if (tag == 'label') {
      return html;
    }
  },
  onIgnoreTagAttr(tag, name, value) {
    // 让 prettyprint 可以工作
    if (tag === 'pre' && name === 'class') {
      return name + '="' + jsxss.escapeAttrValue(value) + '"';
    }
  },
});


module.exports = {
  getBeforeDay(daysAgo) {
    const now = dayjs();
    const numDays = parseInt(daysAgo);

    let unit;
    if (daysAgo.includes('秒')) {
      unit = 'second';
    } else if (daysAgo.includes('分钟')) {
      unit = 'minute';
    } else if (daysAgo.includes('小时')) {
      unit = 'hour';
    } else if (daysAgo.includes('天')) {
      unit = 'day';
    } else if (daysAgo.includes('周')) {
      unit = 'week';
    } else if (daysAgo.includes('月')) {
      unit = 'month';
    } else if (daysAgo.includes('年')) {
      unit = 'year';
    }

    return now.subtract(numDays, unit);
  },

  // 判断是否是移动设备
  isMobile(ua) {
    const mobileKeywords = ['android', 'iphone', 'ipod', 'ipad', 'windows phone', 'blackberry'];
    const lowerCasedUA = ua.toLowerCase();
    return mobileKeywords.some(keyword => lowerCasedUA.includes(keyword));
  },

  cleanTags(tags) {
    if (tags) {
      if (!Array.isArray(tags)) {
        tags = tags.trim().split(/[,，]+/).map(v => v.replace(/\s+/g, ' ').trim()).filter(v => v);
      }
      for (let i = 0; i < tags.length; i++) {
        let tag = tags[i];
        tags[i] = tag.split(' ').map(v => _.upperFirst(v)).join(' ')
          .split('-').map(v => _.upperFirst(v)).join('-');
      }
      tags = [...new Set(tags)];
    }
    return tags;
  },

  getFromUrl(froms, name) {
    for (const item of froms) {
      if (item.name == name) {
        return item.url;
      }
    }
    return null;
  },

  async notifySuperAdmin(author_id, topic_id) {
    const super_admins = this.config.super_admins;
    const super_admin_users = await this.service.userSvc.getUsersByNames(super_admins);
    for (const super_admin_user of super_admin_users) {
      await this.service.messageSvc.sendNewTopicMessage(super_admin_user.id, author_id, topic_id);
    }
  },

  markdown(text) {
    return (
      '<div class="markdown-text markdown-body">' +
      myxss.process(md.render(text || '')) +
      '</div>'
    );
  },

  escapeSignature(signature) {
    return signature
      .split('\n')
      .map(p => {
        return validator.escape(p);
      })
      .join('<br>');
  },

  staticFile(filePath) {
    if (filePath.indexOf('http') === 0 || filePath.indexOf('//') === 0) {
      return filePath;
    }
    return this.app.config.site_static_host + filePath;
  },

  tabName(tab) {
    const pair = this.app.config.tabs.find(pair => {
      return pair[0] === tab;
    });
    if (pair) {
      return pair[1];
    }
    if (tab == 'good') {
      return '推荐';
    }
  },

  proxy(url) {
    return url;
    // 当 google 和 github 封锁严重时，则需要通过服务器代理访问它们的静态资源
    // return '/agent?url=' + encodeURIComponent(url);
  },

  getAnchorId(title) {
    return Buffer.from(title).toString('base64').replace(/[^\w]/g, '').slice(-15);
  },

  highlightKw(keyword, title, type) {
    let segmentKeywords = this.ctx.helper.fenci(keyword);
    if (segmentKeywords.includes('++')) {
      segmentKeywords = segmentKeywords.replace(/\+\+/g, '+\\+');
    }
    const regexpPattern = new RegExp(segmentKeywords, 'ig');
    if (title) {
      return title.replace(regexpPattern, (matchWord) => {
        return `<span class="${type}-keyword-hightlight">${matchWord}</span>`;
      });
    } else {
      return '';
    }
  },

  zhuanyi(text) {
    return text.replace(/\\/g, '\\\\');
  },

  fenci(keyword) {
    let segmentKeyword = this.app.segment.doSegment(keyword, {
      simple: true,
      stripPunctuation: true
    });
    segmentKeyword = segmentKeyword.join('|');
    return segmentKeyword;
  },


  ago(date) {
    date = moment(date);
    return date.fromNow();
  },

  validateId(str) {
    return /^[a-zA-Z0-9\-_\u4e00-\u9fa5]+$/i.test(str);
  },

  bhash(str) {
    return bcrypt.hashSync(str, 10);
  },

  bcompare(str, hash) {
    return bcrypt.compareSync(str, hash);
  },

  uniqueFollowingsOrFans(fans) {
    const tmpSet = new Set();
    return fans.filter((v) => !tmpSet.has(v.name) && tmpSet.add(v.name));
  },


  getUniqueArrayCaseNotSensitive(arr) {
    let result = [];

    for (const v of arr) {
      let flag = true;
      for (const vv of result) {
        if (vv.toLowerCase() == v.toLowerCase()) {
          flag = false;
          break;
        }
      }
      if (flag) {
        result.push(v);
      }
    }
    return result;
  },


  async dd_warn(message) {
    axios.defaults.headers['Content-Type'] = 'application/json; charset=utf-8';
    let url = 'https://oapi.dingtalk.com/robot/send?access_token=20043bd9ed25ee4231cd2a85728eff3cfba2f8022b375d84a5664155cf84a67d';
    let data = {
      text: {
        content: `发生异常, 异常信息为: \n${message}`
      },
      msgtype: "text",
      at: {
        isAtAll: true
      }
    };
    let response = await axios.post(url, data);
  },

  async dd_customize(message) {
    axios.defaults.headers['Content-Type'] = 'application/json; charset=utf-8';
    let url = 'https://oapi.dingtalk.com/robot/send?access_token=20043bd9ed25ee4231cd2a85728eff3cfba2f8022b375d84a5664155cf84a67d';
    let data = {
      text: {
        content: `${message} 发起了新的自定义订阅`
      },
      msgtype: "text",
      at: {
        isAtAll: true
      }
    };
    let response = await axios.post(url, data);
  },


  async dd_push(topics) {
    let links = topics.map(t => {
      return {title: t.title, messageURL: `https://taosha.club/topic/${t.id}`, picURL: t.pic}
    });

    // let url = 'https://oapi.dingtalk.com/robot/send?access_token=dc7da787876567a7e3c8c1aaaf82ec85306f7cb70d05d45c0585d2fb7b499a5a';
    let url = 'https://oapi.dingtalk.com/robot/send?access_token=7bd679501a863a82c774e94ac8c01c798251584f67ef718fedd62c2f6f366b1d';
    let data = {msgtype: 'feedCard', feedCard: {links: links}};

    const response = await got({
      method: 'post',
      url,
      body: JSON.stringify(data),
      headers: {'content-type': 'application/json;charset=utf-8'},
    });
    return response.data;
  },


  getReferer(topic_id) {
    return `/topic/${topic_id}`;
  },

  async autoScrollByLimit(page, bottomHeight) {
    await page.evaluate(async (bottomHeight) => {
      await new Promise((resolve, reject) => {
        var totalHeight = 0;
        var distance = 100;
        var timer = setInterval(() => {
          var scrollHeight = document.body.scrollHeight;
          window.scrollBy(0, distance);
          totalHeight += distance;

          if (totalHeight > bottomHeight) {
            clearInterval(timer);
            resolve();
          } else if (totalHeight >= scrollHeight) {
            clearInterval(timer);
            resolve();
          }
        }, 100);
      });
    }, bottomHeight);
  },


  async autoScrollByLimitSlow(page, bottomHeight) {
    await page.evaluate(async (bottomHeight) => {
      await new Promise((resolve, reject) => {
        var totalHeight = 0;
        var distance = 100;
        var timer = setInterval(() => {
          var scrollHeight = document.body.scrollHeight;
          window.scrollBy(0, distance);
          totalHeight += distance;

          if (totalHeight > bottomHeight) {
            clearInterval(timer);
            resolve();
          } else if (totalHeight >= scrollHeight) {
            clearInterval(timer);
            resolve();
          }
        }, 700);
      });
    }, bottomHeight);
  },


  async getCanUseBrowserAndPage(url, selector, click, scroll, wait) {
    let browser;
    let page = null;
    let element = null;
    let try_cnt = 0;
    while (element == null && try_cnt < 3) {
      try {
        browser = await chromium.launch({headless: true});
        page = await browser.newPage();
        await page.setExtraHTTPHeaders({'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'});
        await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 10000});
        // await page.screenshot({path: 'screenshot/baijiahao-error.png'});

        if (wait) {
          await page.waitForTimeout(wait);
        }

        if (click) {
          await page.waitForSelector(click, {timeout: 10000, state: 'attached'});
          await page.click(click);
          await page.waitForTimeout(5000);
        }

        if (scroll) {
          await this.autoScrollByLimit(page, scroll);
        }

        element = await page.waitForSelector(selector, {timeout: 10000, state: 'attached'});
      } catch (e) {
        // this.logger.warn('获取page失败, 重新尝试', url, e.message);
        if (page) {
          await page.waitForTimeout(3000);
        }
        if (browser) {
          await browser.close();
        }
        try_cnt++;
      }
    }

    if (element == null) {
      if (browser) {
        await browser.close();
      }
      throw new Error('获取page失败: ' + url);
    } else {
      element = null;
      return [browser, page];
    }
  },


  async getMobileCanUseBrowserAndPage(url, selector, click, scroll, wait) {
    let browser;
    let page = null;
    let element = null;
    let try_cnt = 0;
    while (element == null && try_cnt < 3) {
      try {
        browser = await chromium.launch({headless: true});
        const iphone12 = devices['iPhone 12'];
        page = await browser.newPage({
          ...iphone12,
        });
        await page.setExtraHTTPHeaders({'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'});
        await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 10000});
        // await page.screenshot({path: 'screenshot/baijiahao-error.png'});

        if (wait) {
          await page.waitForTimeout(wait);
        }

        if (click) {
          await page.waitForSelector(click, {timeout: 10000, state: 'attached'});
          await page.click(click);
          await page.waitForTimeout(5000);
        }

        if (scroll) {
          await this.autoScrollByLimit(page, scroll);
        }

        element = await page.waitForSelector(selector, {timeout: 10000, state: 'attached'});
      } catch (e) {
        // this.logger.warn('获取page失败, 重新尝试', url, e.message);
        if (page) {
          await page.waitForTimeout(3000);
        }
        if (browser) {
          await browser.close();
        }
        try_cnt++;
      }
    }

    if (element == null) {
      if (browser) {
        await browser.close();
      }
      throw new Error('获取page失败: ' + url);
    } else {
      element = null;
      return [browser, page];
    }
  },


  async getPicInPlaywright(url, selector) {
    const browser = await chromium.launch({headless: true});
    let value;
    try {
      const page = await browser.newPage();
      await page.setExtraHTTPHeaders({'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'});
      await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 10000});
      await page.waitForSelector(selector, {timeout: 10000, state: 'attached'});
      value = await page.$eval(selector, v => v.src);
    } catch (e) {
      this.logger.error(e);
    } finally {
      await browser.close();
      return value;
    }
  },


  betterUniqueTopics(topics) {
    topics.forEach(t => {
      if (!t.tags) {
        t.tags = [];
      }
      if (!t.boards) {
        t.boards = [];
      }
    })

    let result = Object.values(topics.reduce((obj, item) => {
      if (obj[item.title]) {
        obj[item.title] = JSON.parse(JSON.stringify(obj[item.title]));
        for (const tag of item.tags) {
          if (!obj[item.title].tags.includes(tag)) {
            obj[item.title].tags.push(tag);
          }
        }

        for (const board of item.boards) {
          if (!obj[item.title].boards.includes(board)) {
            obj[item.title].boards.push(board);
          }
        }
      } else {
        obj[item.title] = {...item};
      }
      return obj;
    }, {}));
    return result;
  },


  uniqueTopics(topics) {
    const tmpSet = new Set();
    return topics.filter((b) => !tmpSet.has(b.title) && tmpSet.add(b.title));
  },

  setDefaultBoards(topics) {
    let board_map = {
      '下厨房': ['美食']
    }

    topics.forEach(t => {
      for (const key in board_map) {
        if (t.author_name == key) {
          if (!t.boards) {
            t.boards = [];
          }
          t.boards.push(...board_map[key]);
        }
      }
    });
  },


  changeTags(topics) {
    let tag_map = {
      '人工智能': 'AI'
    }

    topics.forEach(t => {
      for (const key in tag_map) {
        if (t.tags) {
          for (let i = 0; i < t.tags.length; i++) {
            if (t.tags[i] == key) {
              t.tags[i] = tag_map[key];
              t.tags = Array.from(new Set(t.tags));
              break;
            }
          }
        }
      }
    });
  },

  setDefaultPic(topics) {
    let pic_arr = [
      ['知乎推荐', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/zhihu_big.jpeg'],
      ['开发者头条', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/kaifazhetoutiao.jpeg'],
      // ['掘金', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/juejin_big.webp'],
      // ['中国歌曲排行榜', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/zhongguogequpaihangbang.webp'],
      // ['搜狐新闻', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora%2Fsohu_default.jpeg'],
      // ['环球网', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/huanqiuwang_big.jpg'],
      // ['IT之家', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/ithome_big.webp'],
      // ['微信热榜', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/weixin_default.webp'],
      // ['ZAKER新闻', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/zaker-big.jpg'],
      // ['第一财经', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/diyicaijing_big.webp'],
      // ['腾讯新闻', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/qqnews.webp'],
      // ['抽屉新热榜', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/chouti_big.webp'],
    ];

    topics.forEach(topic => {
      if (!topic.pic) {
        for (const v of pic_arr) {
          if (topic.author_name == v[0]) {
            topic.pic = v[1];
            break;
          }
        }
      }
    })
  },


  setRealAuthorName(topics) {
    let url_arr = [
      ['thepaper.cn', '澎湃新闻', '6219ca83af06e718ebbcbbd8', '/public/images/pengpai.png'],
      ['huxiu.com', '虎嗅新闻', '6219ca975933df18fafaf73e', '/public/images/huxiu.png'],
      ['guancha.cn', '观察者网', '6215027814ead414b2000280', '/public/images/guancha.png'],
      ['cnbeta.com', 'CnBeta热榜', '629961579ec6114aec610459', '/public/images/cnbeta.png'],
      ['xinhuanet.com', '新华网热榜', '621a1eb06fd07b2457d23d77', '/public/images/xinhuanet.png'],
      ['www.news.cn', '新华网热榜', '621a1eb06fd07b2457d23d77', '/public/images/xinhuanet.png'],
      ['mp.weixin.qq.com', '微信热榜', '6214fc5fed506a11c1cffe79', '/public/images/weixin.png'],
      ['dongqiudi.com', '懂球帝', '6217903c0ca6b665eb94c721', '/public/images/dongqiudi.png'],
      ['douban.com', '豆瓣热榜', '621a277fccbb482888188399', '/public/images/douban.png'],
      ['bilibili.com', 'Bilibili热榜', '62178e8643ab5464a7b15312', '/public/images/bilibili2.png'],
      ['//b23.tv', 'Bilibili热榜', '62178e8643ab5464a7b15312', '/public/images/bilibili2.png'],
      ['1point3acres.com', '一亩三分地', '6219ca6ffbe0cf18caea0660', '/public/images/yimusanfendi.png'],
      ['jiemian.com', '界面新闻', '6219cae43a07421946682580', '/public/images/jiemian.png'],
      ['xilu.com', '西陆网', '6219ca1d0c9f8f188a4e1020', '/public/images/xiluwang.png'],
      ['chouti.com', '抽屉新热榜', '6219cce43e0a1c1a3a2936b7', '/public/images/chouti.png'],
      ['36kr.com', '36Kr', '6219be233e5efc10cb0110d1', '/public/images/36kr.png'],
      ['qbitai.com', '量子位', '6219cfac8d51f01b8aecae74', '/public/images/liangziwei.png'],
      ['www.baidu.com/s?wd=', '百度热搜', '621acb0d17b58e2ccdb97843', '/public/images/baidu.png'],
      ['tieba.baidu.com', '贴吧热议', '6219cb6ecf879819b82df90d', '/public/images/tieba.png'],
      ['zhihu.com', '知乎推荐', '620899babc0e87448a243aad', '/public/images/zhihu.png'],
      ['smzdm.com', '什么值得买', '6209f267cd92e911c3708f05', '/public/images/smzdm.png', ['生活']],
      ['weibo.com', '微博热门', '62091a77ccdeb8821f8f9054', '/public/images/weibo.png'],
      ['weibo.cn', '微博热门', '62091a77ccdeb8821f8f9054', '/public/images/weibo.png'],
      ['sspai.com', '少数派', '6219cf8d1c6fd71b6d972775', '/public/images/shaoshupai.png'],
      ['dgtle.com', '数字尾巴', '6219e595340c9d1fc6ea9912', '/public/images/shuziweiba.png'],
      ['sina.com', '新浪新闻', '6219cd66c65f291a70c30037', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/sina.png'],
      ['jianshu.com', '简书热榜', '6219e5f9e189141fed4fd6a9', '/public/images/jianshu.png'],
      ['ixigua.com', '西瓜视频', '6219e3f4c703d91f08cda773', '/public/images/xigua.png'],
      ['zol.com.cn', '中关村在线', '621503162c9f7f153fa01343', '/public/images/zol.png'],
      ['360doc.com', '360Doc', '6219cd489d0bad1a5394df98', '/public/images/360doc.png'],
      ['autohome.com', '汽车之家', '6219cf0f1ecd3f1b396136e9', '/public/images/autohome.png'],
      // ['myzaker.com', 'ZAKER新闻', '6214ff6a97c6ef139f2cded0', '/public/images/zaker.png'],
      // ['zaker.net', 'ZAKER新闻', '6214ff6a97c6ef139f2cded0', '/public/images/zaker.png'],
      ['leikeji.com', '雷科技热榜', '6219be99cb490510ee589606', '/public/images/leikeji.png'],
      ['infoq.cn', 'InfoQ', '5f743b7915f22a302d318b59', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/infoq.jpg'],
      ['juejin.cn', '掘金', '5f743ad00c1ddb3019f42456', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/juejin.webp'],
      ['segmentfault.com', '思否', '5f743a5cea022430046c0d7d', '/public/images/segmentfault.png'],
      ['oschina.net', '开源中国', '5f74394caa01a12fdd91bce9', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/oschina_big.webp'],
      ['dongchedi.com', '懂车帝热榜', '6219ca35c3974518aa3ae402', '/public/images/dongchedi.png'],
      ['ltaaa.cn', '龙腾网', '621acc609638e92d051b4bdb', '/public/images/longtengwang.png'],
      ['mtime.com', '时光网热榜', '6219caaade07dc19076447bf', '/public/images/mtime.png'],
      ['tmtpost.com', '钛媒体', '6219d1e5c8b2fc1c6a9d6e2d', '/public/images/taimeiti.png'],
      ['donews.com', 'DoNews热榜', '6219e4cfa923001f4d5691d3', '/public/images/donews.png'],
      ['ithome.com', 'IT之家', '62178ff8eb992065cce68dee', '/public/images/ithome.png'],
      ['linux.cn', 'Linux中国', '6219ce31a77c9b1ac314f0e2', '/public/images/linux.png'],
      ['jfdaily.com', '上观新闻', '6219d22da270491c824e6745', '/public/images/shangguan.png'],
      ['dapenti.com', '打喷嚏热榜', '621acf6090f9ec2da708eefe', '/public/images/dapengti.png'],
      ['iyiou.com', '亿欧热榜', '6219e94ad2662b21673a9355', '/public/images/yiou.png'],
      ['toutiao.com', '今日头条', '6219cc8fa587c81a0fc6cfd8', '/public/images/jinritoutiao.png'],
      ['gkzhan.com', '智能制造网', '621ad0b9a9202b2e1c28f025', '/public/images/zhinengzhizaowang.png'],
      ['vmovier.com', '场库热榜', '621a24c65f77132726f2dbe2', '/public/images/changku.png'],
      ['xinpianchang.com', '新片场', '621a237f47c7b42644c3eb8f', '/public/images/xinpianchang.png'],
      ['anquanke.com', '安全客热榜', '6219e6231bc9f8201345efe3', '/public/images/anquanke.png'],
      ['199it.com', '199it热榜', '6219e60d9f0ac42006d6be16', '/public/images/199it.png'],
      ['readhub.cn', 'ReadHub', '6219e5bbdbc2b41fd4b7406b', '/public/images/readhub.png'],
      ['freebuf.com', 'FreeBuf', '6219ce974e44c41af3b39fe0', '/public/images/freebuf.png'],
      ['geekpark.net', '极客公园', '621a2ab9be3ab229a35349ee', '/public/images/jikegongyuan.png'],
      ['zcool.com.cn', '站酷热榜', '6219e6b67ae784204a713468', '/public/images/zhanku.png'],
      ['digitaling.com', '数英每日', '621a29ad14299d2937298690', '/public/images/shuying.png'],
      ['shejipi.com', '设计癖', '6219ccaefdb5681a29fe4aa5', '/public/images/shejipi.png'],
      ['zhiguf.com', '指股网', '6219e4bc4ccdbd1f324129ea', '/public/images/zhiguwang.png'],
      ['csdn.net', 'CSDN热榜', '621ad1dd7d22a52ea2ef7656', '/public/images/csdn.png'],
      ['gcores.com', '机核网', '6219d40494c2c31cc78062c9', '/public/images/jihewang.png'],
      ['fengniao.com', '蜂鸟网', '6219e8d511450820ffe9eddf', '/public/images/fengniaowang.png'],
      ['appinn.com', '小众软件', '6219e9b2346bb9218b79bd31', '/public/images/xiaozhong.png'],
      ['pearvideo.com', '梨视频', '6219ea263df23621c2daf21a', '/public/images/lishipin.png'],
      ['thehour.cn', '小时新闻', '621a2298cbdd33256bbe650c', '/public/images/xiaoshixinwen.png'],
      ['pingwest.com', '品玩热榜', '621a269f96fb082834a7853d', '/public/images/pingwan.png'],
      ['kankanews.com', '看看新闻', '621a27f5d4259428c0896f47', '/public/images/kankanxinwen.png'],
      ['xinli001.com', '壹心理热榜', '621a2459cdf88326d4df59aa', '/public/images/yixinli.png'],
      ['dili360.com', '国家地理', '621a1f1de4fef3247f2949eb', '/public/images/guojiadili.png'],
      ['new.ngchina.cn', '国家地理', '621a1f1de4fef3247f2949eb', '/public/images/guojiadili.png'],
      ['cbndata.com', 'CBNData', '6219e6fade9f522069f648c0', '/public/images/cbndata.png'],
      ['ifanr.com', '爱范热榜', '6219e50a4035561f5e45a971', '/public/images/aifan.png'],
      ['lifeweek.com.cn', '三联生活周刊', '621ae1f96f29303227a51912', '/public/images/sanlian.png'],
      ['bohaishibei.com', '博海拾贝', '61e3d5d46e41fed74ac3b822', '/public/images/bohaishibei.png'],
      ['huanqiukexue.com', '环球科学', '621b4d80578df249ec86203e', '/public/images/huanqiukexue.png'],
      ['yystv.cn', '游研社', '623175e9c23871385745e804', '/public/images/youyanshe.png'],
      ['yicai.com', '第一财经', '623176f1d2e15c3970ccda1f', '/public/images/diyicaijing.png'],
      ['haohaozhu.cn', '好好住', '6231793732e0ac3cc3aab33b', '/public/images/haohaozhu.png'],
      ['chinanews.com', '中国新闻网', '623179a9f52ebf3d7820ca6d', '/public/images/chinanews.png'],
      ['huanqiu.com', '环球网', '62317a06f504883e133b9913', '/public/images/huanqiuwang.png'],
      ['.sohu.com', '搜狐新闻', '62317f42b479c2424a0a0a19', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/sohu.png'],
      ['.chinaipo.com', '资本邦', '62319ff879801e560fdf2ad5', '/public/images/zibenbang.png'],
      ['.aicaijing.com.cn', 'AI财经社', '6231a9feb991515c37f19711', '/public/images/aicaijing.png'],
      ['.cdsb.com', '成都商报', '6231aedc06ce1762327eb060', '/public/images/chengdu.png'],
      ['.techweb.com.cn', 'TechWeb', '6231afcb61bdc0638451fb91', '/public/images/techweb.png'],
      ['.xinmin.cn', '新民网', '6231b1f99e1c2166a8be74e9', '/public/images/xinminwang.png'],
      ['.haiwainet.cn', '海外网', '6231b29d8107ae67c55a82e0', '/public/images/haiwaiwang.png'],
      ['.jrj.com.cn', '金融界', '6231b32743343668d8f6d981', '/public/images/jinrongjie.png'],
      ['.hostloc.com', '全球主机交流论坛', '6231ca83871e60751314720c', '/public/images/quanqiuzhuji.png'],
      ['.bkeconomy.com', '贝壳财经', '6231cd582e8d6b792171c738', '/public/images/beikecaijing.png'],
      ['.chinadaily.com', '中国日报', '6231ce324489597b0da12ced', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/zhongguoribao.jpg'],
      ['.sycaijing.com', '三言财经', '6231cf572bd22f7d1f30d945', '/public/images/sanyancaijing.png'],
      ['.xiachufang.com', '下厨房', '62f9c2186bd16c131e0e4ba8', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/xiachufang.png'],
      ['.163.com', '网易新闻', '62f9db67c178251765694c2b', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/wangyihao.jpg'],
      ['.xcar.com.cn', '爱卡汽车', '62f9dcf6be3fcb1889ea0bb3', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/aikaqiche.jpg'],
      ['new.qq.com', '腾讯新闻', '62ece0288e1f347a5c98bf7b', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/tengxunxinwen.jpg'],
      ['cctvnews.cctv.com', '央视新闻', '62ecaa6d600655615738f8f5', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/ysxw.jpg'],
      ['news.cctv.com', '央视新闻', '62ecaa6d600655615738f8f5', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/ysxw.jpg'],
      ['.ctdsb.net', '极目新闻', '62fa09106db8ec24ced6fa45', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/jimuxinwen.jpg'],
      ['.21jingji.com', '21经济网', '62fa175069234227b635dcf1', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/21jingjiwang.jpg', ['财经']],
      ['.logonews.cn', '标志情报局', '62fa18976224b628899d29d1', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/biaozhiqingbaoju.jpg'],
      ['.okjike.com', '即刻', '62fa1987f8bbea2930772d42', '/public/images/jike.png'],
      ['.mafengwo.cn', '马蜂窝', '620b78dab551e146e725a837', '/public/images/mafengwo.png'],
      ['.gamersky.com', '游民星空', '62fa1ba2498ff02a903cd790', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/youminxingkong.jpg'],
      ['.chaihezi.com', '拆盒', '62fa1d10a301192c43f2efdb', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/chaihezi.jpg'],
      ['.lanxiongsports.com', '懒熊体育', '62fa1ebf89afc02df695ad10', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/lanxiongtiyu.jpg'],
      ['.bjnews.com.cn', '新京报', '62fa1fec6f944e2ea8df70d2', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/xinjingbao.jpg'],
      ['.toodaylab.com', '理想生活实验室', '62fa2102c86c0b2f7a5df80b', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/lixiangshenghuoshiyanshi.jpg'],
      ['.cnu.cc', 'CNU视觉联盟', '62fa42acc5100432c0e9098c', 'https://taosha01-1253585015.cos.ap-shanghai.myqcloud.com/typora/shijuelianmeng.jpg'],
    ];


    topics.forEach(topic => {
      if (!topic.boards) {
        topic.boards = [];
      }
      if (!topic.tags) {
        topic.tags = [];
      }

      for (const v of url_arr) {
        if (topic.content.includes(v[0])) {
          topic.author_name = topic.sub_tab = v[1];
          topic.author_id = v[2];
          topic.author_avatar = v[3];
          topic.boards = [...topic.boards];
          if (v[4]) {
            topic.boards = topic.boards.concat(v[4]);
          }
          topic.tags = [...topic.tags];
          if (!topic.boards.includes('抽屉')) {
            topic.boards.push('抽屉');
          }
          break;
        }
      }
    });
  },


  permuteArr(keyword) {
    let result = [];
    let tmp_arr = keyword.trim().split(/\s+/);
    result.push(tmp_arr.join('.*'));
    if (tmp_arr.length > 1) {
      result.push(tmp_arr.reverse().join('.*'));
    }

    return result;
  },


  setTechBoard(topic) {
    const title = topic.title.toLowerCase();

    // 架构
    if (title.includes('架构') || title.includes('分布式')
      || title.includes('系统设计') || title.includes('微服务')
      || title.includes('可用性') || title.includes('伸缩性')
      || title.includes('负载均衡') || title.includes('容器化')
    ) {
      topic.boards.push('架构');
    }


    // 后端
    if (title.includes('Java') || title.includes('python')
      || title.includes('node.js') || title.includes('go')
      || title.includes('php') || title.includes('c#')
      || title.includes('.net') || title.includes('spring')
      || title.includes('django') || title.includes('服务器')
      || title.includes('微服务') || title.includes('后端框架')
    ) {
      topic.boards.push('后端');
    }

    // 前端
    if (title.includes('前端') || title.includes('javascript')
      || title.includes('react') || title.includes('vue')
      || title.includes('angular') || title.includes('flutter')
      || title.includes('less') || title.includes('sass')
      || title.includes('css') || title.includes('ecmascript')
      || title.includes('webpack') || title.includes('vite')
      || title.includes('样式') || title.includes('localStorage')
    ) {
      topic.boards.push('前端');
    }


    // 测试
    if (title.includes('测') || title.includes('缺陷')) {
      topic.boards.push('测试');
    }

    // AI·大数据
    if (title.includes('人工智能') || title.includes('ai')
      || title.includes('机器学习') || title.includes('深度学习')
      || title.includes('大数据') || title.includes('数据挖掘')
      || title.includes('神经网络') || title.includes('tensorflow')
      || title.includes('pytorch') || title.includes('强化学习')
      || title.includes('数据仓库') || title.includes('etl')
    ) {
      topic.boards.push('AI·大数据');
    }

    // 数据库
    if (title.includes('数据库') || title.includes('mysql')
      || title.includes('oracle') || title.includes('mongo')
      || title.includes('tidb') || title.includes('sql')
      || title.includes('hbase') || title.includes('关系数据库')
      || title.includes('数据建模') || title.includes('事务')
      || title.includes('索引') || title.includes('事务')
    ) {
      topic.boards.push('数据库');
    }


    // 技术周刊
    if (title.includes('周刊') || title.includes('周报')
      || title.includes('掘金一周')) {
      topic.boards.push('技术周刊');
    }


    if (!topic.boards.length) {
      topic.boards.push('其他');
    }

  }

}


